//
//  EditGridConnectedViewController.swift
//  GreenDeal
//
//  Created by Moennig Q on 29/12/2022.
//

import UIKit
import RxSwift
import RxCocoa

class EditGridConnectedViewController: BaseViewController {
    var refreshDetailClosure: (()->Void)?
    private lazy var disposeBag = DisposeBag()
    let customView = EditGridConnectedView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.gridConnected())
        let viewModel = GridConnectedViewModel()
        var connectedType: GridConnectedValue = .offGrid
        if let type = GridConnectedValue(rawValue: JobDetailModelHelper.shared.jobDetailModel.system_detail.connected_type){
            connectedType = type
        }
        viewModel.connected_type = connectedType
        viewModel.nmi = JobDetailModelHelper.shared.jobDetailModel.install_address.nmi
        viewModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
        viewModel.isNMIRequired = JobDetailModelHelper.shared.jobDetailModel.install_address.isNMIRequired
        viewModel.gridConnectionApplicationRefNo = JobDetailModelHelper.shared.jobDetailModel.install_address.grid_connection_application_ref_no
        self.customView.setData(viewModel)
        //
        self.customView.saveBtn.rx.tap.subscribe {[weak self] _ in
            self?.saveDataInfo()
        }.disposed(by: self.disposeBag)
    }
    private func saveDataInfo(){
        self.view.endEditing(true)
        let vm = EditJobInfoService()
        vm.setBlockAfterNetwork {[weak self] (result, _) in
            guard let strongSelf = self else {return}
            ModelViewUtil.shared.hideUpdatingView()
            strongSelf.refreshDetailClosure?()//connected type的修改影响到影响noc的必填项属性，所以要及时刷新
            strongSelf.navigationController?.popViewController(animated: true)
        } errorBlock: { (code, error) in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error)
        }
        ModelViewUtil.shared.showLoadingView(R.string.localizable.updating())
        vm.updateGridConnected(self.customView.gridConnectedView.viewModel)
    }
}
